
const mysql = require('mysql');

const connect = mysql.createPool({
  port: 3306,
  host: '47.101.45.245',
  user: '1809a-commuity',
  database: '1809a-commuity',
  password: 'ZktM5BAHx8jzzJtJ'
})

const exec = (sql, params) => {
  return new Promise((resolve, reject) => {
    connect.query(sql, params, (err, data) => {
      if (err) reject(err);
      resolve(data)
    })
  })
}

exec(`SELECT * FROM cartGoods;`).then(res => {
  console.log('res: ', res)
})

const jwt = require('jsonwebtoken')


module.exports = {
  lintOnSave: false,
  devServer: {
    before(app) {

      const db = [
        {
          user: 'devin',
          pwd: '123'
        }
      ]

      app.get('/api/register', async(req, res, next) => {
        const { userName, password } = req.query;
        const data = await exec(
          `insert into users (userName, password) values (?, ?)`, [userName, password]
          )
        console.log('data:', data)
        res.send({
          code: 0,
          msg: 'success',
          data
        })
      })

      // 用户信息接口
      app.get('/api/userInfo', (req, res, next) => {
        console.log(req.headers, '头部信息')
        const { token } = req.headers;
        try{
          const data = jwt.verify(token, 'key')
          res.send({
            code: 0,
            msg: 'success',
            data: {
              userId: [0],
              userInfo: {
                nickname: 'devin',
                age: 123,
                address: '上海市奉贤区',
                avatar: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Falcdn.img.xiaoka.tv%2F20161019%2F7e9%2F304%2F34561699%2F7e930479e72e9d3c31e8cdebfa4668e3.jpg%401e_1c_0o_0l_640h_640w_90q_1pr.jpg&refer=http%3A%2F%2Falcdn.img.xiaoka.tv&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1626577293&t=698ba9c65a6c006f1e7c99544d291897'
              }
            }
          })
        } catch(err) {
          res.send({
            code: -1,
            msg: 'fail',
          })
        }
      })

      // 登陆授权接口
      app.get('/api/login', (req, res, next) => {
        const { userName, pwd } = req.query;
        const loginStatus = db.some(v => v.user === userName && v.pwd === pwd)
        if (loginStatus) {
          const token = jwt.sign({ userName }, 'key', { expiresIn: '1h' })
          res.send({
            code: 0,
            msg: 'success',
            data: {
              token
            }
          })
        } else {
          res.send({
            code: -1,
            msg: 'fail'
          })
        }
      })
    }
  }
}
